<template>
  <div class="app-container">
    <div class="container">
      <div class="main page page-list">
        <div class="head-container">
          <el-card shadow="never">
            <div class="search-bar">
              <el-form size="mini" :inline="true" :model="searchModel">
                <el-form-item label="发票类型:">
                  <el-radio-group
                    @change="search(1)"
                    v-model="searchModel.invoiceType"
                  >
                    <el-radio-button label="">不限</el-radio-button>
                    <el-radio-button :label="0">增值税专用发票</el-radio-button>
                    <el-radio-button :label="1">增值税普通发票</el-radio-button>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="商户编号:">
                  <el-input
                    size="mini"
                    v-model="searchModel.userId"
                    placeholder="商户编号"
                  ></el-input>
                </el-form-item>

                <el-form-item label="发票号码:">
                  <el-input
                    size="mini"
                    v-model="searchModel.invoiceNumber"
                    placeholder="发票号码"
                  ></el-input>
                </el-form-item>

                <el-form-item label="申请开票时间">
                  <el-date-picker
                    v-model="searchModel.createTime"
                    :default-time="['00:00:00']"
                    type="datetimerange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd HH:mm:ss"
                  />
                </el-form-item>

                <el-form-item class="operations">
                  <el-button type="primary" @click="search(1)">查询</el-button>
                  <el-button type="default" @click="reset">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </div>

        <el-card shadow="never">
          <el-table
            size="mini"
            v-loading="loading"
            ref="multipleTable"
            :data="tableData"
            highlight-current-row
          >
         
            <el-table-column label="发票编号">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.id }}
                </div>
              </template>
            </el-table-column>

               <el-table-column label="商户编号">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.userId }}
                </div>
              </template>
            </el-table-column>

            <el-table-column label="申请开票时间">
              <template slot-scope="scope">
                {{ scope.row.createTime }}
              </template>
            </el-table-column>

            <el-table-column label="发票抬头">
              <template slot-scope="scope">
                <span>{{ scope.row.invoiceTitle }}</span>
              </template>
            </el-table-column>

            <el-table-column label="发票类型">
              <template slot-scope="scope">
                <span v-if="scope.row.invoiceType === 0">增值税专用发票</span>
                <span v-if="scope.row.invoiceType === 1">增值税普通发票</span>
              </template>
            </el-table-column>
            <el-table-column label="发票介质">
              <template slot-scope="scope">
                <span v-if="scope.row.invoiceMaterial === 0">电子发票</span>
                <span v-if="scope.row.invoiceMaterial === 1">纸质发票</span>
              </template>
            </el-table-column>

            <el-table-column label="发票号码">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.invoiceNumber ? scope.row.invoiceNumber : "-" }}
                </div>
              </template>
            </el-table-column>

            <el-table-column label="发票金额">
              <template slot-scope="scope">
                <div>{{ scope.row.invoiceAmount }}元</div>
              </template>
            </el-table-column>

            <el-table-column label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.invoiceStatus === 'wait'">待开票</span>
                <span v-if="scope.row.invoiceStatus === 'dealing'">开票中</span>
                <span
                  v-if="scope.row.invoiceStatus === 'success'"
                  class="text-success"
                  >开票成功</span
                >
                <span
                  v-if="scope.row.invoiceStatus === 'mailed'"
                  class="text-success"
                  >已邮寄</span
                >
                <span
                  v-if="scope.row.invoiceStatus === 'fail'"
                  class="text-danger"
                  >开票失败</span
                >
              </template>
            </el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <div class="ops">
                  <el-button
                    style="margin-left: 10px"
                    slot="reference"
                    size="mini"
                    type="text"
                    @click="invoiceDetails(scope.row)"
                    >详情
                  </el-button>

                  <el-button
                    style="margin-left: 10px"
                    slot="reference"
                    size="mini"
                    type="text"
                    v-if="scope.row.invoiceStatus === 'dealing'"
                    @click="openInvoice(scope.row)"
                    >开票
                  </el-button>

                  <el-button
                    style="margin-left: 10px"
                    slot="reference"
                    size="mini"
                    type="text"
                    v-if="scope.row.invoiceStatus === 'dealing'"
                    @click="openInvoiceFail(scope.row)"
                    >开票失败
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-row class="paging-wrap">
            <el-col :span="24">
              <el-pagination
                :current-page="searchModel.pageNo"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="searchModel.pageSize"
                layout="prev, pager, next, sizes, jumper"
                @size-change="PageSizeChange"
                @current-change="PageChange"
                :total="searchModel.count"
              >
              </el-pagination>
            </el-col>
          </el-row>
        </el-card>
      </div>
      <!-- 开具发票 -->
      <el-dialog
        title="开具发票"
        :visible.sync="mailingDialog"
        width="550px"
        :modal-append-to-body="false"
      >
        <el-form
          class="m-t-24"
          ref="openInvoiceFrom"
          size="small"
          :rules="rules"
          :model="openInvoiceFrom"
          label-width="140px"
          autocomplete="off"
        >
          <el-form-item
            label="邮寄单号"
            prop="expressNumber"
            v-if="submitOpenInvoiceFrom.invoiceMaterial === 1"
          >
            <el-input
              v-model="openInvoiceFrom.expressNumber"
              placeholder="请输入邮寄单号"
            ></el-input>
          </el-form-item>

          <el-form-item label="发票号码" prop="invoiceNumber">
            <el-input
              v-model="openInvoiceFrom.invoiceNumber"
              placeholder="请输入发票号码"
            ></el-input>
          </el-form-item>

          <el-form-item label="电子发票图片" prop="invoicePage" v-if="submitOpenInvoiceFrom.invoiceMaterial === 0">
            <el-upload
            class="avatar-uploader"
              action="/api/admin/image"
              :show-file-list="false"
              name="file"
              accept="image/jpeg,image/png,application/pdf"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
            <img
                  v-if="openInvoiceFrom.invoicePage"
                  :src="openInvoiceFrom.invoicePage"
                  class="avatar"
                />
           <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>

            
          </el-form-item>

          <el-form-item style="text-align: right; margin: 40px 0 0 0">
            <el-button @click="mailingDialog = false">取消</el-button>
            <el-button
              type="primary"
              :loading="openInvoiceLoading"
              @click="confirmsOpenInvoice"
              >确定</el-button
            >
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 开票失败 -->
      <el-dialog
        title="开票失败"
        :visible.sync="failDialog"
        width="550px"
        :modal-append-to-body="false"
      >
        <el-form
          class="m-t-24"
          ref="failFrom"
          size="small"
          :rules="rules"
          :model="failFrom"
          label-width="140px"
          autocomplete="off"
        >
          <el-form-item label="失败原因" prop="failMessage">
            <el-input
              type="textarea"
              :rows="2"
              v-model="failFrom.failMessage"
              placeholder="请输入失败原因"
            ></el-input>
          </el-form-item>

          <el-form-item style="text-align: right; margin: 40px 0 0 0">
            <el-button @click="failDialog = false">取消</el-button>
            <el-button
              type="primary"
              :loading="failLoading"
              @click="confirmsOpenInvoiceFail"
              >确定</el-button
            >
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>


<script>
import { searchInvoice, openInvoice, openInvoiceFail } from "@/api/business";
import pickerOptions from "../../utils/options";
let defaultSearchModel = {
  pageSize: 10,
  pageNo: 1,
  count: null,
  invoiceType: "",
  userId: null,
  invoiceNumber: null,
  createTime: null,
};
export default {
  data() {
    return {
      searchModel: _.cloneDeep(defaultSearchModel),
      loading: false,
      mailingDialog: false,
      opLoading: false,
      failDialog: false,
      openInvoiceFrom: {
        invoiceNumber: "",
        expressNumber: "",
        invoicePage:""
      },
      failFrom: {
        failMessage: "",
      },
      openInvoiceLoading: false,
      failLoading: false,
      tableData: [],
      pickerOptions,
      submitOpenInvoiceFrom: {
        userId: null,
        id: null,
        invoiceMaterial: null,
      },
      submitFailFrom: {
        userId: null,
        id: null,
      },
      rules: {
        expressNumber: [
          {
            required: true,
            message: "请输入邮寄单号",
          },
        ],
        invoiceNumber: [{ required: true, message: "请选择发票号码" }],
        invoicePage: [{ required: true, message: "请选择电子发票图片",min: 1,
            max: 1 }],
      },
    };
  },

  components: {},
  methods: {
    search(pageNo) {
      this.loading = true;
      if (pageNo) {
        this.searchModel.pageNo = pageNo;
      }
      let searchModel = _.cloneDeep(this.searchModel);
      this.compileSearchModel(searchModel);
      searchInvoice(searchModel)
        .then((res) => {
          if (res.success) {
            this.loading = false;
            this.searchModel.count = res.count;
            this.tableData = res.data;
          } else {
            this.searchModel.count = 0;
            this.tableData = [];
          }
        })
        .catch((err) => {
          console.log(err);
          this.searchModel.count = 0;
          this.tableData = [];
        });
    },
    //发票详情
    invoiceDetails(row) {
      let invocieData = row;
      localStorage.setItem("INVOICE_DETAILS", JSON.stringify(invocieData));
      this.$router.push("/userManage/invoiceDetails");
    },
    //开票失败
    openInvoiceFail(row) {
      this.failDialog = true;
      this.submitFailFrom.id = row.id;
      this.submitFailFrom.userId = row.userId;
    },
    //确认开票失败
    confirmsOpenInvoiceFail() {
      this.failLoading = true;
      let form = {
        id: this.submitFailFrom.id,
        userId: this.submitFailFrom.userId,
        failMessage: this.failFrom.failMessage,
      };
      openInvoiceFail(form)
        .then((resp) => {
          if (resp.success) {
            this.$notify({
              title: "操作成功",
              type: "success",
              duration: 2500,
            });
            this.search(0);
          }
          this.failDialog = false;
          this.failLoading = false;
        })
        .catch((err) => {});
    },
    //开票
    openInvoice(row) {
      this.mailingDialog = true;
      this.openInvoiceFrom = {
         invoiceNumber: "",
        expressNumber: "",
        invoicePage:"",
        invoiceType:""
      };
      this.submitOpenInvoiceFrom.id = row.id;
      this.submitOpenInvoiceFrom.userId = row.userId;
      this.submitOpenInvoiceFrom.invoiceMaterial = row.invoiceMaterial;

    },
    //确认开票
    confirmsOpenInvoice() {
      this.openInvoiceLoading = true;
      let form = {
        userId: this.submitOpenInvoiceFrom.userId,
        id: this.submitOpenInvoiceFrom.id,
        invoiceMaterial: this.submitOpenInvoiceFrom.invoiceMaterial,
        invoiceNumber: this.openInvoiceFrom.invoiceNumber,
        expressNumber: this.openInvoiceFrom.expressNumber,
        invoicePage: this.openInvoiceFrom.invoicePage,
      };
      if(form.invoiceMaterial === 0 && form.invoicePage === ""  ){
         this.$notify({
              title: "电子发票图片不能为空",
              type: "error",
            });
           this.openInvoiceLoading = false;
      }else{
           openInvoice(form)
        .then((resp) => {
          if (resp.success) {
            this.$message.success("开具发票成功");
            this.search(0);
            
          }
          this.openInvoiceLoading = false;
          this.mailingDialog = false;
        })
        .catch((err) => {});
      }
   
    },

    handleAvatarSuccess(res, file) {
      this.openInvoiceFrom.invoicePage = res.data;
    },

    beforeAvatarUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error("上传大小不能超过 5MB!");
      }
      return isLt5M;
    },
    compileSearchModel(searchModel) {
      if (searchModel.createTime) {
        searchModel.createMinTime = searchModel.createTime[0];
        searchModel.createMaxTime = searchModel.createTime[1];
      }

      searchModel.pageNo = searchModel.pageNo - 1;

      delete searchModel.createTime;
    },

    /**
     * 页数改变
     * @param data 改变后的页数
     * @constructor
     */
    PageChange(data) {
      this.searchModel.pageNo = data;
      this.search();
    },
    /**
     * 单页条数改变
     * @param data 改变后的条数
     * @constructor
     */
    PageSizeChange(data) {
      this.searchModel.pageSize = data;
      this.search();
    },
    reset() {
      this.searchModel = _.cloneDeep(defaultSearchModel);
      this.search();
    },
  },
  mounted() {
    this.search();
  },
};
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 246px;
    height: 138px;
    line-height: 138px;
    background-color: #fff;
    text-align: center;
  }
  .avatar {
    width: 246px;
    height: 138px;
    display: block;
  }

  .avatar-uploader1 .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader1 .el-upload:hover {
    border-color: #409eff;
  }

  
</style>
<style lang="scss" scoped>
 
.ops {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}
</style>
